var MY_STAFF = (function() {
	
	/**
	 * 提取可以使用（已购买）的账号
	 * 更新时，默认当前已有的账号
	 */
	function getAccountTypeOptions(defaultAccount) {
		var options = '';
		if (defaultAccount) {// 修改成员信息时，本身的账号type
			options += '<option value="' + defaultAccount.id + '">';
				options += defaultAccount.name
			options += '</option>';
		}
		
//		// 门诊账号
//		options += '<option value="103">门诊账号</option>';
		
/*		$.ajax({
	        type: "POST",
	        url: "wncrm_loginuser_manage.do/getAccountType",
	        dataType: "json",
	        async: false,
	        success: function(data) {
	        	if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
	        	if (data.errorcode == 0 && data.accountList.length) {
	        		$(data.accountList).each(function(idx, account) {
	        			if (!defaultAccount || defaultAccount.id != account.accounttypeId) { // 不等于默认账号
		        			options += '<option value="' + account.accounttypeId + '">';
		        				options += account.name;
		        			options += '</option>';
	        			}
	        		});
	        	}
	        }
		});*/
		return options;
	}
	
	function prepareAddStaff() {
		var $staffSection = $('section#staff');
		
		// 账户类型
		var $accountType = $staffSection.find('select[name="accountType"]');
		$accountType.empty();
		var accountHtml = getAccountTypeOptions();
		// if (!accountHtml && !accountHtml.lenght) { // 没有可用账号
		// 	$('section#staff, setion#org').hide();
		// 	$('section#guide-buy').show(0, function() {
		// 		$('section#guide-buy button[name="back"]').one('click', function() { // 返回
		// 			$('section#guide-buy').hide(function() {
		// 				$('section#org').show();
		// 			})
		// 		});
		// 	});
		// } else {
			$staffSection.show();
		// }
		$accountType.append(accountHtml);
		
		// 部门选择
		var $selectOrg = $staffSection.find('select[name="orgId"]');
		$selectOrg.empty();
		var options = '';
		$('nav#orgStruct li[data-orgid][data-orgname]').each(function(idx, org) {
			var $org = $(org);
			var level = parseInt($org.data('level'));
			options += '<option value="' + $org.data('orgid') + '"' + ($org.hasClass('active')?'selected="selected"':'') + '>';
				while(--level > 0) {
					options += ' ';
				}
				options += $org.data('orgname');
			options += '</option>';
		});
		$selectOrg.append(options);
		
		// 诊所门诊
		var $dptCd = $staffSection.find('select[name="clinicDptCd"]');
		if (!$dptCd.text().length) {
			$dptCd.append(MY_CLINIC_DPT_COMMON.createSelectBody());
		}
		
		$staffSection.find('button[name="remove"]').hide(); // 隐藏删除按钮
		$staffSection.find('input[name="name"]').val('').focus();
		$staffSection.find('input[name="phone"]').val('');
		$staffSection.find('input[name="isManager"][value="0"]').prop('checked', true);
		$staffSection.find('input[name="loginUser"]').val('');
		$staffSection.find('input[name="loginPassword"]').val('').attr("placeholder", "6-16字符，支持数字/字母/下划线").attr("disabled", false);
		//$staffSection.find('div[name="confirmLoginPasswordDiv"]').hide();
		$staffSection.find('label.title').text('新建成员');
		
		if (WeKnow.isYbNetwork()) { // 医保工作模式
			$staffSection.find('input[name="cityYbDoctorServiceNb"]').val('');
			$staffSection.find('input[name="doctorCredentialsCode"]').val('');
//			$staffSection.find('input[name="provinceYbDoctorServiceNb"]').val('');
		}
	}
	
	function prepareReplaceStaff(staff) {
		var $staffSection = $('section#staff');
		$staffSection.data('doctoruuid', staff.doctorUUID);
		
		// 账户类型
		var $accountType = $staffSection.find('select[name="accountType"]');
		$accountType.empty();
		var accountHtml = getAccountTypeOptions({
			id: staff.accounttypeId,
			name: staff.accounttypeName
		});// 存在本身的账号类型，所以肯定存在内容
		$accountType.append(accountHtml);
		$staffSection.show();
		
		// 部门选择
		var $selectOrg = $staffSection.find('select[name="orgId"]');
		$selectOrg.empty();
		var options = '';
		$('nav#orgStruct li[data-orgid][data-orgname]').each(function(idx, org) {
			var $org = $(org);
			var level = parseInt($org.data('level'));
			options += '<option value="' + $org.data('orgid') + '"' + ($org.data('orgid')==staff.orgId?'selected="selected"':'') + '>';
				while(--level > 0) {
					options += ' ';
				}
				options += $org.data('orgname');
			options += '</option>';
		});
		$selectOrg.append(options);
		
		// 诊所门诊
		var $dptCd = $staffSection.find('select[name="clinicDptCd"]');
		$dptCd.html(MY_CLINIC_DPT_COMMON.createSelectBody(staff.clinicDptCd));
		
		$staffSection.find('button[name="remove"]').show(); // 显示删除按钮
		$staffSection.find('input[name="name"]').val(staff.name);
		$staffSection.find('input[name="cityYbDoctorServiceName"]').val(staff.cityYbDoctorServiceName);
		$staffSection.find('input[name="phone"]').val(staff.phone);
		$staffSection.find('input[name="isManager"][value="' + staff.isManager + '"]').prop('checked', true);
		$staffSection.find('select[name="accountType"]').val(staff.accounttypeId);
		$staffSection.find('input[name="loginUser"]').val(staff.loginUser);
		$staffSection.find('input[name="loginPassword"]').val('').attr("placeholder","不修改密码则无需输入新密码");;
		//是自己的账号可以修改密码
		/*var doctorUUID = $("#doctorUUID").val();
		if(doctorUUID == staff.doctorUUID){
			$staffSection.find('input[name="loginPassword"]').val('').attr("disabled", false);
			//$staffSection.find('div[name="confirmLoginPasswordDiv"]').show();
		}else{
			$staffSection.find('input[name="loginPassword"]').val('******').attr("disabled", true);
			//$staffSection.find('div[name="confirmLoginPasswordDiv"]').hide();
		}*/
		$staffSection.find('label.title').text('修改成员信息');
		$staffSection.find('select[name="role"]').val(staff.role);

		if (staff.role == 1) {//角色是医生时，显示相关输入框
			$('.is-doctor').show();
		} else {
			$('.is-doctor').hide();
		}
		
		if (WeKnow.isYbNetwork()) {
			$staffSection.find('input[name="cityYbDoctorServiceNb"]').val(staff.cityYbDoctorServiceNb);
			$staffSection.find('input[name="doctorCredentialsCode"]').val(staff.doctorCredentialsCode);
//			$staffSection.find('input[name="provinceYbDoctorServiceNb"]').val(staff.provinceYbDoctorServiceNb);
		}
	}
	
	/**
	 * staff list 一行数据
	 */
	function buildStaffOneRecord(staff) { // DtInvsOrganizationStructureStaffEntity.java
		console.log(staff)
		var e = '';
		e += '<tr';
			e += ' data-name="' + staff.doctor.name + '"';
			e += ' data-phone="' + staff.doctor.phone + '"';
			e += ' data-loginuser="' + staff.account.loginUser + '"';
			e += ' data-ismanager="' + staff.isManager + '"';
			e += ' data-accounttypeid="' + staff.account.accounttypeId + '"';
			e += ' data-accounttypename="' + staff.account.accounttypeName + '"';
			e += ' data-role="' + (staff.account.role==null?1:staff.account.role) + '"';
			if (WeKnow.isYbNetwork()) {
				e += ' data-cityybdoctorservicenb="' + staff.account.cityYbDoctorServiceNb + '"';
				e += ' data-cityybdoctorservicename="' + staff.account.cityYbDoctorServiceName + '"';
				e += ' data-doctorcredentialscode="' + staff.account.doctorCredentialsCode + '"';
//				e += ' data-provinceybdoctorservicenb="' + staff.account.provinceYbDoctorServiceNb + '"';
				e += ' data-citydptcd="' + staff.account.cityDptCd + '"';
				e += ' data-provincedptcd="' + staff.account.provinceDptCd + '"';
			}
			e += ' data-orgid="' + staff.org.id + '"';
			if (staff.account.dptCd != null) {
				e += ' data-clinicdptcd="' + staff.account.dptCd + '"';
			}
			e += ' data-doctoruuid="' + staff.doctorUUID + '"';
			e += '>';
			e += '<td>' + staff.doctor.name + '</td>';
			e += '<td>' + staff.account.loginUser + '</td>';
			e += '<td class="text-center">' + new Date(staff.account.validBeginDt).format("yyyy-MM-dd") + '</td>';
			e += '<td>' + staff.org.name + '</td>';
			e += '<td class="text-center">' + (staff.isManager ? '<span style="color: #d9534f;" data-toggle="tooltip" data-placement="bottom" title="可以查看同部门其他成员的客户">是</span>' : '否') + '</td>';
			e += '<td class="text-center">';
				e += '<div class="btn-group">';
					e += '<button type="button" class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">设置<span class="caret"></span></button>';
					e += '<ul class="dropdown-menu dropdown-menu-right">';
						// e += '<li><a href="javascript:void(0);" name="resetpw">重置密码</a></li>';
						e += '<li><a href="javascript:void(0);" name="menuMinus">菜单权限</a></li>';
					e += '</ul>';
				e += '</div>';
				//e += '<button type="button" name="resetpw" class="btn btn-xs btn-default">重置密码</button> ';
				e += '&nbsp;<button type="button" name="replaceStaff" class="btn btn-xs btn-default">编辑</button>';
			e += '</td>';
		e += '</tr>';
		return e;
	}
	
	/**
	 * 成员列表
	 */
	function listStaff(orgId, orgName) {
		var $org = $('section#org');
		$org.data('id', orgId); // 用于后续修改等
		$org.data('name', orgName); // 用于后续修改等
		
		// 页面头部显示部门信息
		$org.find('#orgName').text(orgName);
		$org.find('#orgStaffCnt').text(0);
		
		var params = {};
		
		$.ajax({
	        type: "POST", 
	        url: "wncrm_org_struct.do/staff/list", 
	        dataType: "json",
	        data: {
	        	orgId: orgId
	        },
	        async: false,
	        success: function(staffs) {
	        	if (!WeKnow.filterAjaxResult(staffs)) return false; // session过期check
	        	var $orgBody = $('section#org table tbody');
	        	$orgBody.empty();
	        	if (staffs && staffs.length) {
	        		var e = '';
	        		$(staffs).each(function(idx, staff) {
	        			e += MY_STAFF.buildStaffOneRecord(staff);
	        		});
	        		$orgBody.append(e);
	        		// 部门人数
	        		$org.find('#orgStaffCnt').text(staffs.length);
	        	} else {
	        		WeKnow.notifyMsg('当前部门成员0位');
	        	}
	        },
	        error: function() {
	        	var $orgBody = $('section#org table tbody');
	        	$orgBody.empty();
	        	WeKnow.notifyMsg('当前部门成员0位');
	        }
		});
	}
	
	// add by zhengxb 2018.4.9 start-------------------------------------
	/**
	 * 成员列表(根据名字筛选)
	 */
	function listStaffByName(orgId,searchKeyName) {
		
		var $org = $('section#org');
		$org.data('id', orgId); // 用于后续修改等
//		$org.data('name', orgName); // 用于后续修改等
		
		// 页面头部显示部门信息
//		$org.find('#orgName').text(orgName);
		$org.find('#orgStaffCnt').text(0);
		var params = {};
		params.orgId = orgId;
		params.searchKeyName = searchKeyName;
		
		$.ajax({
	        type: "POST", 
	        url: "wncrm_org_struct.do/staff/listbyname", 
	        dataType: "json",
	        data: params,
	        async: false,
	        success: function(staffs) {
	        	if (!WeKnow.filterAjaxResult(staffs)) return false; // session过期check
	        	var $orgBody = $('section#org table tbody');
	        	$orgBody.empty();
	        	if (staffs && staffs.length) {
	        		var e = '';
	        		$(staffs).each(function(idx, staff) {
	        			e += MY_STAFF.buildStaffOneRecord(staff);
	        		});
	        		$orgBody.append(e);
	        		// 部门人数
	        		$org.find('#orgStaffCnt').text(staffs.length);
	        	} else {
	        		//WeKnow.notifyMsg('没有匹配成员');
	        	}
	        },
	        error: function() {
	        	var $orgBody = $('section#org table tbody');
	        	$orgBody.empty();
	        	//WeKnow.notifyMsg('没有匹配成员');
	        }
		});
	}
	// add by zhengxb 2018.4.9 end-------------------------------------
	
	/**
	 * 新建成员
	 */
	function add() {
		var params = {};
		var $staffSection = $('section#staff');

		params.name = $.trim($staffSection.find('input[name="name"]').val());

		params.loginUser = $.trim($staffSection.find('input[name="loginUser"]').val());
		if (!params.loginUser.length) {
			WeKnow.errorMsg('请输入用户名');
			$staffSection.find('input[name="loginUser"]').focus();
			return false;
		} else {
			if (MY_VALIDATOR.isContinueChar(params.loginUser)) {
				WeKnow.errorMsg('请不要使用连续字符作为用户名');
				$staffSection.find('input[name="loginUser"]').focus();
				return false;
			}
		}
		params.loginPassword = $.trim($staffSection.find('input[name="loginPassword"]').val());
		if (!params.loginPassword.length) {
			WeKnow.errorMsg('请输入密码');
			$staffSection.find('input[name="loginPassword"]').focus();
			return false;
		} else {
			if (params.loginPassword.length < 6) {
				WeKnow.errorMsg('密码至少有6位');
				$staffSection.find('input[name="loginPassword"]').focus();
				return false;
			} else if (MY_VALIDATOR.isContinueChar(params.loginPassword)) {
				WeKnow.errorMsg('请不要使用连续字符作为密码');
				$staffSection.find('input[name="loginPassword"]').focus();
				return false;
			}
		}
		
		// 部门
		var $org = $staffSection.find('select[name="orgId"]');
		params.orgId = $org.val();

		// 管理员
		params.isManager = $staffSection.find('input[name="isManager"]:checked').val();
		
		WeKnow.loading();
		$.ajax({
	        type: "POST", 
	        url: "wncrm_loginuser_manage.do/add", 
	        dataType: "json",      
	        data: params,
	        async: false,
	        success: function(data) {
        		if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
	        	
        		if (data.errorcode == 0) {
        			
    				$('nav#orgStruct li[data-orgid="' + $org.val() + '"]').click();
    				WeKnow.successMsg("新建成员成功");
//    				$('p.freeaccounts span').text(data.freeAccountCnt);
				} else {
					WeKnow.errorMsg(data.errormsg ? data.errormsg : "新建成员失败");
				}
	        },
	        error: function() {
	        	WeKnow.errorMsg("系统异常");
	        }
		});
		WeKnow.closeLoading();
	}
	
	/**
	 * 修改成员信息
	 */
	function replace() {
		var params = {};
		var $staffSection = $('section#staff');
		params.doctorUUID = $staffSection.data('doctoruuid');
		
		params.name = $.trim($staffSection.find('input[name="name"]').val());
		if (!params.name.length) {
			WeKnow.errorMsg('请输入姓名');
			$staffSection.find('input[name="name"]').focus();
			return false;
		}

		$staffSection.find('div[name="orgName"]').val();
		params.isManager = $staffSection.find('input[name="isManager"]:checked').val();
		params.loginUser = $.trim($staffSection.find('input[name="loginUser"]').val());
		if (!params.loginUser.length) {
			WeKnow.errorMsg('请输入用户名');
			$staffSection.find('input[name="loginUser"]').focus();
			return false;
		} else {
			if (MY_VALIDATOR.isContinueChar(params.loginUser)) {
				WeKnow.errorMsg('请不要使用连续字符作为用户名');
				$staffSection.find('input[name="loginUser"]').focus();
				return false;
			}
		}
		
		// 部门
		var $org = $staffSection.find('select[name="orgId"]');
		params.orgId = $org.val();

		// 管理员
		params.isManager = $staffSection.find('input[name="isManager"]:checked').val();

		//是否修改密码
		var password = $.trim($staffSection.find('input[name="loginPassword"]').val());
		if (password.length) {
			if (password.length < 6) {
				WeKnow.errorMsg('密码至少有6位');
				$staffSection.find('input[name="loginPassword"]').focus();
				return false;
			} else if (MY_VALIDATOR.isContinueChar(password)) {
				WeKnow.errorMsg('请不要使用连续字符作为密码');
				$staffSection.find('input[name="loginPassword"]').focus();
				return false;
			}
			params.loginPassword = password;
		}

		WeKnow.loading();
		$.ajax({
	        type: "POST", 
	        url: "wncrm_loginuser_manage.do/replace", 
	        dataType: "json",      
	        data: params,
	        async: false,
	        success: function(data) {
        		if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
	        	
        		if (data.errorcode == 0) {
        			WeKnow.successMsg("修改成功");
    				$('nav#orgStruct li[data-orgid="' + $org.val() + '"]').click(); // 显示登录部门的list
//        			$('nav#orgStruct li.active').click();
				} else {
					WeKnow.errorMsg(data.errormsg ? data.errormsg : "修改失败");
				}
	        },
	        error: function() {
	        	WeKnow.errorMsg("系统异常");
	        }
		});
		WeKnow.closeLoading();
	}
	
	function ybDptInit(cityDptCd, provinceDptCd) {

		//加载医保科室
		var postUrl = "wncrm_his_account/get_dptinfo";
		var params = {};
		$.post(postUrl, params, function(data, status) {
			if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
			if(data.errorcode == 0) {
				//有市医保
				if (data.cityDptList) {
					$('#cityDpt').empty();
					$(data.cityDptList).each(function(idx, dpt) {
						if (cityDptCd && dpt.dptCd == cityDptCd) {
							$('#cityDpt').append('<option  value="' + dpt.dptCd + '" selected="selected" >' + dpt.dptName + '</option>');
						} else {
							$('#cityDpt').append('<option  value="' + dpt.dptCd + '" >' + dpt.dptName + '</option>');
						}
					});
				}
				//有省医保
				if (data.provinceDptList) {
					$('#provinceDpt').empty();
					$(data.provinceDptList).each(function(idx, dpt) {
						if (provinceDptCd && dpt.dptCd == provinceDptCd) {
							$('#provinceDpt').append('<option  value="' + dpt.dptCd + '" selected="selected" >' + dpt.dptName + '</option>');
						} else {
							$('#provinceDpt').append('<option  value="' + dpt.dptCd + '" >' + dpt.dptName + '</option>');
						}
					});
				}
			}
		});
	}
	
	return {
		prepareAddStaff: prepareAddStaff,
		prepareReplaceStaff: prepareReplaceStaff,
		buildStaffOneRecord: buildStaffOneRecord,
		listStaff: listStaff,
		add: add,
		replace: replace,
		listStaffByName:listStaffByName,
		ybDptInit: ybDptInit
	}
})();


$(document).ready(function() {
	// 添加成员 & 修改成员信息
	$('section#org').on('click', 'button[name="addMember"], button[name="replaceStaff"]', function() {
		var $that = $(this);
//		var $orgSection = $('section#org');
		var $staffSection = $('section#staff');
		
		if ($that.attr('name') === 'addMember') {
			$staffSection.attr('operate', 'add'); // 新建成员
			$('section#org').hide(function() {
				MY_STAFF.prepareAddStaff();
				//显示医保科室
				MY_STAFF.ybDptInit();
			});
		} else if ($that.attr('name') === 'replaceStaff') { // 修改成员信息
			$staffSection.attr('operate', 'replace');
			$('section#org').hide(function() {
				var $staffTr = $that.closest('tr');
				var staff = {};
				staff.name = $staffTr.data('name');
				staff.phone = $staffTr.data('phone');
				staff.isManager = $staffTr.data('ismanager');
				staff.accounttypeId = $staffTr.data('accounttypeid');
				staff.accounttypeName = $staffTr.data('accounttypename');
				staff.loginUser = $staffTr.data('loginuser');
				staff.doctorUUID = $staffTr.data('doctoruuid');
				staff.orgId = $staffTr.data('orgid');
				staff.clinicDptCd = $staffTr.data('clinicdptcd');
				staff.cityYbDoctorServiceNb = $staffTr.data('cityybdoctorservicenb');
				staff.cityYbDoctorServiceName = $staffTr.data('cityybdoctorservicename');
				staff.doctorCredentialsCode = $staffTr.data('doctorcredentialscode');
//				staff.provinceYbDoctorServiceNb = $staffTr.data('provinceybdoctorservicenb');
				staff.role = $staffTr.data('role');
				MY_STAFF.prepareReplaceStaff(staff);
				//显示医保科室
				MY_STAFF.ybDptInit($staffTr.data('citydptcd'), $staffTr.data('provincedptcd'));
			});
		}
		
		// 取消
		$staffSection.find('button[name="cancel"]').one('click', function() {
			$staffSection.hide(function() {
				$('section#org').show();
			});
		});
	});
	
	// 密码重置 
	$('section#org').on('click', 'a[name="resetpw"]', function() {
		var $that = $(this);
		var $attr = $that.closest('tr');
		var doctorUUID = $attr.data('doctoruuid');
		WeKnow.confirm(
			'确定给 #' + $attr.data('name') + '# 重置密码？<br>默认密码：123456',
			function() {
				$.ajax({
			        type: "POST", 
			        url: "wncrm_pwd_manage.do/reset", 
			        dataType: "json",
			        data: {
			        	doctorUUID: doctorUUID
			        },
			        async: false,
			        success: function(data) {
			        	if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
			        	if (data.errorcode == 0) {
			        		WeKnow.successMsg('密码重置成功');
			        	} else {
			        		WeKnow.errorMsg('密码重置失败');
			        	}
			        },
			        error: function() {
			        	WeKnow.systemMsg('系统异常');
			        }
				});
			});
	});
	
	// 保存
	$('section#staff button[name="save"]').on('click', function() {
		var $that = $(this);
		var $staffSection = $('section#staff');
		if ($staffSection.attr('operate') === 'add') { // 新建成员
			MY_STAFF.add();
		} else if ($staffSection.attr('operate') === 'replace') { // 修改成员信息
			MY_STAFF.replace();
		}
	});
	
	// 删除
	$('section#staff button[name="remove"]').on('click', function() {
		var $that = $(this);
		var $staffSection = $('section#staff');
		var doctorUUID = $staffSection.data('doctoruuid');
		WeKnow.confirm(
			'删除后无法回退，确定删除？',
			function() {
				$.ajax({
			        type: "POST", 
			        url: "wncrm_loginuser_manage.do/remove", 
			        dataType: "json",
			        data: {
			        	doctorUUID: doctorUUID
			        },
			        async: false,
			        success: function(data) {
			        	if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
			        	if (data.errorcode == 0) {
			        		WeKnow.successMsg('删除成功');
			        		$('nav#orgStruct li.active').click();
//			        		$('p.freeaccounts span').text(data.freeAccountCnt);
			        	} else if (data.errorcode == -2) {
			        		WeKnow.errorMsg('无法删除自己');
			        	} else {
							WeKnow.errorMsg(data.errormsg ? data.errormsg : "删除失败");
			        	}
			        },
			        error: function() {
			        	WeKnow.systemMsg('系统异常');
			        }
				});
			}
		);
	});

	// 选择角色时
	$('section#staff select[name="role"]').on('change', function() {
		var $that = $(this);
		console.log($that.val());
		if ($that.val() == 1) {
			$('.is-doctor').show();
		} else {
			$('.is-doctor').hide();
		}
	});
});